#include "Thread.hpp"
#include <pthread.h>
#include <unistd.h>
std::string GetThreadName()
{
    static int i = 1; // 定义在里面更好
    char namebuffer[64];
    snprintf(namebuffer, sizeof(namebuffer) - 1, "thread-%d", i++);
    return namebuffer;
}

class ThreadData
{
public:
    ThreadData(const std::string &threadname, pthread_mutex_t *mutex) // 这里对应mutex是赋值
        : _threadname(threadname), _mutex(mutex)
    {
    }

public:
    std::string _threadname;
    pthread_mutex_t *_mutex;
};

int ticket = 10000;
void GetTicket(ThreadData *data)
{
    while (true)
    {
        pthread_mutex_lock(data->_mutex);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s: get ticket: %d\n", data->_threadname.c_str(), ticket--);
            pthread_mutex_unlock(data->_mutex);
        }
        else
        {
            pthread_mutex_unlock(data->_mutex);
            break;
        }
    }
}

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, nullptr);

    std::string name1 = GetThreadName();
    ThreadData data1(name1, &mutex);
    Thread<ThreadData *> thread1(name1, GetTicket, &data1);

    std::string name2 = GetThreadName();
    ThreadData data2(name2, &mutex);
    Thread<ThreadData *> thread2(name2, GetTicket, &data2);

    std::string name3 = GetThreadName();
    ThreadData data3(name3, &mutex);
    Thread<ThreadData *> thread3(name3, GetTicket, &data3);

    std::string name4 = GetThreadName();
    ThreadData data4(name4, &mutex);
    Thread<ThreadData *> thread4(name4, GetTicket, &data4);

    thread1.Start();
    thread2.Start();
    thread3.Start();
    thread4.Start();

    thread1.Join();
    thread2.Join();
    thread3.Join();
    thread4.Join();
}